package ru.sviridov.sellandbuy;

import ru.sviridov.sellandbuy.model.query.QueryPasswordQuestion;
import ru.sviridov.sellandbuy.model.query.QueryRenewPassword;
import ru.sviridov.sellandbuy.tasks.base.BaseTask;
import ru.sviridov.sellandbuy.tasks.recipients.GetPasswordRecipient;
import ru.sviridov.sellandbuy.tasks.recipients.RestorePasswordRecipient;
import ru.sviridov.sellandbuy.url.APIGroup;
import ru.sviridov.sellandbuy.url.APIMethod;
import ru.sviridov.sellandbuy.url.URL;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RestoreActivity extends Activity{
	
	private BaseTask<Void> task;
	private EditText etUserName;
	private EditText etAnswer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ContentViewMapper.setContentView(this);
		
		etUserName = (EditText) findViewById(R.id.etUserName);
		etAnswer =  (EditText) findViewById(R.id.etAnswer);
	}
	
	public void onClickGetQuestion(View view){
		if(task!=null && task.getStatus()!=AsyncTask.Status.FINISHED)
			task.cancel(true);
		
		QueryPasswordQuestion query = new QueryPasswordQuestion();
		query.setUserName(etUserName.getText().toString());
		
		task = new BaseTask<Void>(this, new GetPasswordRecipient());
		task.setQueryParams(query);
		task.execute(URL.getURL(APIGroup.MEMBERSHIP, APIMethod.GET_QUESTION));
		
		Toast.makeText(this, "Getting question...", Toast.LENGTH_SHORT).show();	
		etUserName.setEnabled(false);
	}

	public void onClickRestore(View view){
		if(task!=null && task.getStatus()!=AsyncTask.Status.FINISHED)
			task.cancel(true);		
		
		QueryRenewPassword query = new QueryRenewPassword();
		query.setUserName(etUserName.getText().toString());
		query.setPasswordAnswer(etAnswer.getText().toString());
		
		task = new BaseTask<Void>(this, new RestorePasswordRecipient());
		task.setQueryParams(query);
		task.execute(URL.getURL(APIGroup.MEMBERSHIP, APIMethod.RENEW_PASSWORD));
		
		Toast.makeText(this, "Restoring password...", Toast.LENGTH_SHORT).show();
	}
	
	public void setQuestion(String passwordQuestion) {
		findViewById(R.id.btnGetQuestion).setVisibility(View.GONE);
		findViewById(R.id.llQuestion).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.tvQuestion)).setText(passwordQuestion);
	}
}
